package com.inspur.cloud.configuration;

import com.inspur.cloud.service.dataspace.ScheduledService;
import com.inspur.cloud.service.dataspace.UserManagerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class ScheduledConfig {

    @Autowired
    private UserManagerService userManagerService;

    @Autowired
    private ScheduledService scheduledService;

    @Autowired
    private ApiConfig apiConfig;

    private static final Logger logger = LoggerFactory.getLogger(ScheduledConfig.class);

    /**
     * 每天0点更新所有失败次数为0
     */
    @Scheduled(cron = "0 0 0 * * *")
    public void userFailureTimesScheduled() {
        if (!apiConfig.isSchedule()) {
            return;
        }
        try {
            logger.info("开始执行userFailureTimesScheduled" + new Date());
            userManagerService.updateUserFailureTimes();
            logger.info("结束执行userFailureTimesScheduled" + new Date());
        } catch (Exception e) {
            logger.error("userFailureTimesScheduled执行失败");
        }

    }

    /**
     * 每一小时更新admin的失败次数
     */
    @Scheduled(cron = "0 0 0/1 * * *")
    public void adminFailureTimesScheduled() {
        if (!apiConfig.isSchedule()) {
            return;
        }
        try {
            logger.info("开始执行adminFailureTimesScheduled" + new Date());
            userManagerService.updateAdminFailureTimes();
            logger.info("结束执行adminFailureTimesScheduled" + new Date());
        } catch (Exception e) {
            logger.error("adminFailureTimesScheduled执行失败");
        }
    }

    /**
     * 删除无用数据
     */
    @Scheduled(cron = "0 0 1 * * *")
    public void deleteUnusedData() {
        if (!apiConfig.isSchedule()) {
            return;
        }
        try {
            logger.info("开始执行deleteUnusedData" + new Date());
            scheduledService.deleteUnusedData();
            logger.info("结束执行deleteUnusedData" + new Date());
        } catch (Exception e) {
            logger.error("deleteUnusedData执行失败");
        }

    }
}
